import os
os.environ["PROJ_LIB"] = r'C:\Users\ckpark\anaconda3\Library\share'

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy.ma as ma
import scipy.stats as ss
import properscoring as ps
from scipy.stats import iqr
from scipy.stats import linregress
from pylab import plot, show, savefig, xlim, figure, \
                ylim, legend, boxplot, setp, axes
                
import random
import numpy as np
rng = np.random.default_rng()
from scipy.stats import bootstrap

def init_plotting():
    plt.rcParams['font.family'] = 'Times New Roman'
init_plotting()

def color_box(bp, color, alpha):

    # Define the elements to color. You can also add medians, fliers and means
    elements = ['boxes','caps','whiskers','fliers']

    # Iterate over each of the elements changing the color
    for elem in elements:
        [plt.setp(bp[elem][idx], color=color, alpha=alpha) for idx in range(len(bp[elem]))]
    return

subx_list = ['ECCC-GEPS7','EMC-GEFSv12_CPC','ESRL-FIMr1p1','GMAO-GEOS_V2p1','RSMAS-CCSM4','NRL-NESM','NCEP-CFSv2']

sc = []
for i in range(len(subx_list)):
    read = np.loadtxt('../5.SubX/RESULT/SubX_'+subx_list[i], ndmin=2, dtype='str')
    ens = np.array(read[:,0], dtype='int')  
    sc.append(len(ens))

subx = np.zeros((len(subx_list),np.max(sc)))

for i in range(len(subx_list)):
    read = np.loadtxt('../5.SubX/RESULT/SubX_'+subx_list[i], ndmin=2, dtype='str')
    s_var = np.array(read[:,1], dtype='float')  
    
    subx[i,:sc[i]] = s_var

cc = 0; a = 0; b = 0
for t in range(len(subx_list)):
    for x in range(sc[t]):
        if subx[t,x] >= 132:
            a += 1
        if subx[t,x] >= 198:
            b += 1
        cc += 1
        
print('dro_week_ens : ',(a/cc)*100)
print('dro_recov_ens : ',(b/cc)*100)
        

nt = len(subx_list)
fig = plt.figure(figsize=(12,4))
xlab = ['ECCC'+'\n'+'GEPS7','EMC'+'\n'+'GEFSv12','ESRL'+'\n'+'FIMr1p1',\
        'GMAO'+'\n'+'GEOS_V2p1','RSMAS'+'\n'+'CCSM4','NRL'+'\n'+'NESM','NCEP'+'\n'+'CFSv2']
for xx in range(1):
    ax1 = fig.add_subplot(1,1,xx+1)

    xax = np.arange(0,nt)
    xticks = np.arange(0,nt)
    
    for t in range(nt):
       
        ameanlineprops = dict(linestyle='solid', linewidth=2.5, color='black')
        amedianprops = dict(linestyle='none', linewidth=2.5, color='black')
            
        amean = np.mean(subx[t,:sc[t]])

        aflierprops = dict(color='black')
           
        violin_parts = ax1.violinplot(subx[t,:sc[t]], positions =[t], showmeans=False,\
                       showmedians=False,showextrema=True)  
        
        ax1.scatter(t-0.008,amean,color='red',s=100,zorder=10)
        
        for partname in ('cbars','cmins','cmaxes'):
            vp = violin_parts[partname]
            vp.set_edgecolor('gray')
            vp.set_linewidth(2)
      
        for vp in violin_parts['bodies']:
            vp.set_facecolor('gray')
            #vp.set_edgecolor(rrred)
            #vp.set_linewidth(1)
            #vp.set_alpha(0.5)
           

    ax1.axhline(y=132, color='green', linestyle='solid')
    ax1.axhline(y=198, color='blue', linestyle='dashed')
   
    ax1.set_xticklabels(xlab)
    ax1.set_xticks(xticks)
    

    ax1.set_yticks(np.arange(0,310,100))
    ax1.set_ylabel('Accumulated'+'\n'+'precipitation (mm)',fontsize=26)

    #ax1.set_yticks(np.arange(-100,1400,1000))
    #ax1.set_ylim(0,500)
      
    ax1.tick_params(labelsize=20)
    #if pp == 0:
    #    ax1.legend(loc=4,fontsize=20)
    

    ax1.set_xlabel('Model',fontsize=26)


plt.subplots_adjust(hspace=0.2,wspace=0.0)
plt.show()      
outfig = '../99.FIG/each_subx_model_box.png'      
fig.savefig(outfig,bbox_inches='tight')
